package com.qiyu.jvm.reference;

import java.util.Arrays;

/**
 * 设计连通分量来管理两个数值是否有关联
 *
 * @Author linhao
 * @Date created in 3:14 下午 2021/1/4
 */
public class ReferenceCountImpl implements ReferenceCount {

    private int[] arr;

    private int size;

    @Override
    public boolean addNum(int size) {
        arr = new int[size];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = 0;
        }
        this.size = size;
        return false;
    }

    /**
     * 后者连向前者
     * @param a
     * @param b
     * @return
     */
    @Override
    public boolean union(int a, int b) {
        if (arr[a] == 0) {
            arr[a] = a;
            if (arr[b] == 0) {
                arr[b] = a;
            } else {
                arr[b] = a;
            }
        } else {
            arr[b] = arr[a];
        }
        return true;
    }

    @Override
    public boolean isConnected(int a, int b) {
        return arr[a] == arr[b];
    }


    @Override
    public void display() {
        System.out.println(Arrays.toString(arr));
    }


    public static void main(String[] args) {
        ReferenceCount referenceCount = new ReferenceCountImpl();
        referenceCount.addNum(10);
        referenceCount.union(1, 2);
        referenceCount.union(1, 3);
        referenceCount.union(4, 3);
        referenceCount.union(1, 5);
        System.out.println(referenceCount.isConnected(1,2));
        System.out.println(referenceCount.isConnected(1,4));
        System.out.println(referenceCount.isConnected(3,4));
        referenceCount.display();
    }
}
